package com.rop.znyx.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rop.znyx.common.exception.BizException;
import com.rop.znyx.common.result.ResultCodeEnum;
import com.rop.znyx.sys.mapper.RegionWareMapper;
import com.rop.znyx.model.sys.RegionWare;
import com.rop.znyx.sys.service.RegionWareService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rop.znyx.vo.sys.RegionWareQueryVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 城市仓库关联表 服务实现类
 * </p>
 *
 * @author rop
 * @since 2023-06-22
 */
@Service
@RequiredArgsConstructor
public class RegionWareServiceImpl extends ServiceImpl<RegionWareMapper, RegionWare> implements RegionWareService {

    private final RegionWareMapper regionWareMapper;

    /**
     * 列表查询
     */
    @Override
    public IPage<RegionWare> selectPage(Page<RegionWare> pageParam, RegionWareQueryVo regionWareQueryVo) {
        // 条件
        String keyword = regionWareQueryVo.getKeyword();

        LambdaQueryWrapper<RegionWare> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(RegionWare::getRegionName, keyword)
                    .or().like(RegionWare::getWareName, keyword);
        }

        return baseMapper.selectPage(pageParam, queryWrapper);
    }

    /**
     * 添加开通区域
     */
    @Override
    public void saveRegionWare(RegionWare regionWare) {
        // 查询该区域是否已经开通
        LambdaQueryWrapper<RegionWare> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RegionWare::getRegionId, regionWare.getRegionId());
        Integer count = baseMapper.selectCount(queryWrapper);

        // 如果查询出结果大于0，表明该区域已经开通，无需二次开通
        if (count > 0) {
            BizException.error(ResultCodeEnum.REGION_OPEN);
        }

        // 未开通，则开通
        baseMapper.insert(regionWare);
    }

    /**
     * 取消/开通区域
     */
    @Override
    public Boolean updateStatus(Long id, Integer status) {
        RegionWare entity = new RegionWare();
        entity.setId(id);
        entity.setStatus(status);
        int rows = baseMapper.updateById(entity);
        return rows < 0 ? Boolean.FALSE : Boolean.TRUE;
    }
}
